package com.guli.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.guli.auth.feign.MemberFeign;
import com.guli.auth.service.OAuth2Service;
import com.guli.auth.utils.HttpUtils;
import com.guli.auth.vo.SocialUser;
import com.guli.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author zzb
 * @Date 2024/5/29 17:04
 * @Version 1.0
 * @description
 */
@Service
@Slf4j
public class OAuth2ServiceImpl implements OAuth2Service {

    @Autowired
    private MemberFeign memberFeign;

    @Override
    public String weiboLogin(String code, HttpSession session) {
        Map<String, String> map = new HashMap<>();
        //登录成功回掉时携带的参数
        map.put("client_id", "2805964477");
        map.put("client_secret", "06f07c21ceeaf8f34b765cb7aeb24560");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code", code);
        try {
            HttpResponse response = HttpUtils
                    .doPost("https://api.weibo.com", "/oauth2/access_token",
                            "get", new HashMap<>(), null, map);
            //处理
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                String json = EntityUtils.toString(response.getEntity());
                SocialUser socialUser = JSON.parseObject(json, SocialUser.class);
                //知道当前是哪个社交账号
                //1、当前用户如果是第一次进网站，自动注册进来(为当前社交用户生成一个会员信息账号，以后这个社交账号就指定对饮的会员)
                R login = memberFeign.oauthLogin(socialUser);
                if ((Integer) login.get("code") == 0) {
                    Object data = login.get("data");
                    log.info("账号登录成功{}", data);
                    //TODO 使用JSON的序列化方式来序列化对象数据到redis中
                    session.setAttribute("loginUser", data);
                    return "redirect:http://gulimall.com";
                } else {
                    return "redirect:http://auth.gulimall.com/login.html";
                }
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //根据code换取access_token
        return "redirect:http://gulimall.com";
    }
}
